package com.wjc.wjc.service;


import com.wjc.wjc.dao.NewRepository;
import com.wjc.wjc.unity.News;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
public class NewServiceImpl implements NewService{

    @Autowired
    private NewRepository newRepository;

    @Transactional
    @Override
    public News saveNew(News news) {
        news.setCrateTime(new Date());
        return newRepository.save(news);
    }

    @Override
    public News getNew(Long id) {
        return newRepository.getOne(id);
    }

    @Override
    public Page<News> listNews(Pageable pageable) {
        return newRepository.findAll(pageable);
    }

    @Transactional
    @Override
    public News updateNew(Long id, News news) {
        News t=newRepository.getOne(id);
        if (t==null){
            try {
                throw new Exception("不存在");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        BeanUtils.copyProperties(news,t);
        t.setCrateTime(new Date());
        return newRepository.save(t);
    }

    @Transactional
    @Override
    public void deleteNew(Long id) {
        newRepository.deleteById(id);
    }

    @Override
    public List<News> listNews() {
        Sort.Order order=new Sort.Order(Sort.Direction.DESC, "id");
        return newRepository.findAll(Sort.by(order));
    }
}
